<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\ExceptionSms;
use App\Models\Admin;
use App\Models\AdminMenu;
use App\Models\AdminRole;
use App\Requests\AdminRole\StoreRequest;
use Carbon\Carbon;

/**
 * 角色管理
 * Class RoleController
 * @package App\Http\Controllers\Admin
 */
class RoleController extends CommonController
{
    public function index()
    {
        $search_forms = Admin::getForms(['user_name']);

        $cols = [[
            ['field' => 'name', 'title' => '名称'],
            ['field' => 'action', 'title' => '操作', 'escape' => false],
        ]];

        $permission_code = 'role-query';
        $uri             = '/admin/role/list?code=' . $permission_code;

        $top_btns = [
            ['code' => 'role-add']
        ];

        return view('components.list', compact('search_forms', 'cols', 'permission_code', 'uri', 'top_btns'));
    }

    public function dataList()
    {
        $list = AdminRole::bgBaseQuery($this->input())->paginate($this->limit);
        foreach ($list as $resource) {
            $resource->action = '';
            if ($resource->id > 1) {
                $resource->action = $resource->setRowBtns(['role-edit', 'role-delete'], []);
            }
        }

        return ExceptionSms::homeList($list->items(), $list->total());
    }

    // 表单
    public function editAdd()
    {
        $id         = $this->input('id');
        $data       = $id ? AdminRole::getOneById($id) : null;
        $save_forms = [
            ['field' => 'name', 'title' => '名称', 'type' => 'text'],
            ['field' => 'menu_ids', 'title' => '权限', 'type' => 'tree', 'value' => $data ? array_map('intval', $data->menu_ids) : [], 'options' => $this->getMenuTreeA()],
        ];

        $permission_code = $id ? 'role-edit-save' : 'role-add-save';
        return view('components.save_form', compact('save_forms', 'data', 'permission_code'));
    }

    public function getMenuTreeA()
    {
        $list             = AdminMenu::get();
        $permission_trees = [];
        /** @var AdminMenu $resource */
        foreach ($list as $resource) {
            $permission_trees[] = [
                'id'       => $resource->id,
                'title'    => $resource->name,
                'parentId' => $resource->pid,
                'checkArr' => [
                    [
                        'type'    => 0,
                        'checked' => 0,
                    ]
                ],
            ];
        }
        return array_to_tree($permission_trees, 'id', 'parentId', 'children', '0');
    }

    public function dataSave(StoreRequest $request)
    {
        $id = $request->id;

        $data             = $id ? AdminRole::getOneById($id) : new AdminRole();
        $menu_ids         = $request->menu_ids;
        $menu_ids         = explode(',', $menu_ids);
        $data->name       = $request->name;
        $data->menu_ids   = $menu_ids;
        $data->menu_texts = AdminMenu::whereIds($menu_ids)->pluck('name')->toArray();
        $data->save();
        return ExceptionSms::returnSuccess();
    }

    public function deletes()
    {

        $ids = $this->input('ids') ?? [];
        if (!is_array($ids)) ExceptionSms::returnError('请求参数错误');
        if (!collect($ids)->count()) ExceptionSms::returnError('请勾选数据');

        $list = AdminRole::whereIsSuper(0)->whereIds($ids)->get();
        /** @var AdminRole $role */
        foreach ($list as $role) {
            $admin = $role->admin;
            if ($admin) ExceptionSms::returnError("{$role->name}：此角色存在账号，无法删除");
        }

        AdminRole::whereIsSuper(0)->whereIds($ids)->update([
            'is_delete'  => 1,
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
        return ExceptionSms::returnSuccess();
    }
}
